package api

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"net/http"
	"strconv"
	"two_exam/config"
	"two_exam/internal/model/service"
)

var (
	upgrade = websocket.Upgrader{
		WriteBufferSize: 1024,
		ReadBufferSize:  1024,
		//允许跨域
		CheckOrigin: func(r *http.Request) bool {
			return true
		},
	}
)

type Node struct {
	wsConn *websocket.Conn
	data   chan []byte
}

var clientMap = make(map[int]*Node)

func Chat(c *gin.Context) {

	userId, _ := strconv.Atoi(c.Query("userId"))
	friend_id, _ := strconv.Atoi(c.Query("friend_id"))
	friend := service.IsExistsFriend(userId, friend_id)
	if !friend {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "两人不是好友,请添加好友"})
		return
	}
	//升级websocket
	client, err := upgrade.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		return
	}
	node := &Node{
		wsConn: client,
		data:   make(chan []byte, 1024),
	}
	//指定接收人
	clientMap[friend_id] = node
	//发送消息
	go sendMessage(node)
	//读取消息
	go readMessage(node)
}
func sendMessage(node *Node) {
	//服务端发送信息
	for {
		select {
		case data := <-node.data:
			err := node.wsConn.WriteMessage(websocket.CloseMessage, data)
			if err != nil {
				return
			}
		}
	}
}
func readMessage(node *Node) {

	//服务端读取信息
	for {
		_, message, err := node.wsConn.ReadMessage()
		if err != nil {
			return
		}
		sendMessageToUser(message)
	}
}

type Message struct {
	ContentType int    `json:"content_type"`
	UserId      int    `json:"user_id"`
	FriendId    int    `json:"friend_id"`
	Content     string `json:"content"`
}

func sendMessageToUser(message []byte) {
	var messages Message
	err := json.Unmarshal(message, &messages)
	if err != nil {
		return
	}
	//入库
	SaveMessageToDB(&messages)
	//发送给指定用户好友
	SendTo(message, messages.FriendId)

}

func SendTo(message []byte, id int) {
	//服务端接收到转发给某一个用户
	node, ok := clientMap[id]
	if ok {
		node.data <- message
	}
}

func SaveMessageToDB(m *Message) {
	//入库
	err := config.DB.Create(&m).Error
	if err != nil {
		return
	}
}
